package com.bxd.baodan.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ListView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.bxd.baodan.App;
import com.bxd.baodan.R;
import com.bxd.baodan.adapter.CommonAdapter;
import com.bxd.baodan.adapter.ViewHolder;
import com.bxd.baodan.app.LoginInfo;
import com.bxd.baodan.util.JSONUtil;
import com.bxd.baodan.util.LogUtil;
import com.bxd.baodan.util.NetUtil;
import com.bxd.baodan.util.StringUtil;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * 只是为了解决软键盘遮挡输入框的问题. adjust_pan和baseactivity中的状态栏布局是问题的原因.
 */

public abstract class BaseListActivity_<T> extends AppCompatActivity implements View.OnClickListener {
    protected PullToRefreshListView refView;
    protected int page = 0;

    protected CommonAdapter adapter;
    protected boolean canLoadMore = true;
    public static final int OFFSET = 10;


    protected PullToRefreshBase.Mode mode;

    public NetUtil getNetUtil() {
        return netUtil;
    }

    public void setNetUtil(NetUtil netUtil) {
        this.netUtil = netUtil;
    }

    protected NetUtil netUtil;

    protected List<T> mData = new ArrayList<>();
    //防止data是类类型的,需要进一步确定数组对应的字段
    protected ListView listView;
    protected View footer;

    protected Context context;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //布局
        setContentView(getActivityLayout());
        context = this;


        refView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);
        footer = View.inflate(this, R.layout.list_null_footer, null);
        listView = refView.getRefreshableView();
        page = 1;

        //添加头布局
        addHeadView();
        //   setNetUtil();
        adapter = new CommonAdapter<T>(this, mData, getItemLayout()) {
            @Override
            public void convert(ViewHolder holder, T item) {
                BaseListActivity_.this.convert(holder, item);
            }
        };
        initRefresh();
        refView.setAdapter(adapter);

        //添加过头view的操作
        preDone();

        //
        preBundle(savedInstanceState);
        // TODO: 2017/7/7 可能有坑
        try {
            setNetUtil();
        } catch (Exception e) {
            LogUtil.e("setUsualNetUtil: " + e.getMessage());
        }

    }


    protected void initRefresh() {
        setMode();
        refView.setMode(mode == null ? PullToRefreshBase.Mode.BOTH : mode);
        refView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                page = 1;
                canLoadMore = true;
                getData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {

                if (canLoadMore) {
                    page++;
                    getData();
                } else {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    refView.onRefreshComplete();
                                }
                            });
                        }
                    }).start();
                }
            }
        });
    }

    protected void getData() {
        if (netUtil == null) {
            setNetUtil();
        }
        setNetParams();
        initData();
    }


    private void initData() {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {


                String jsonStr = netUtil.postStringResult();


                LogUtil.e("data: " + jsonStr);
                //   jsonStr = " {\"code\":0,\"tips\":\"\",\"data\":[]}";
                parseJsonStr(jsonStr);
                if (JSONUtil.isSuccess(jsonStr)) {
                    e.onNext(jsonStr);
                } else {
                    final String msg = JSONUtil.getMessage(jsonStr);


                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (!StringUtil.isEmpty(msg)) {
                               // showToast(msg);
                            }
                        }
                    });

                }
                e.onComplete();
            }
        }).map(new Function<String, List<T>>() {
            @Override
            public List<T> apply(String s) throws Exception {
                final String json_data = JSONUtil.getData(s);

                if (json_data.startsWith("[")) {
                    LogUtil.e("data--is--array");
                    return new Gson().fromJson(json_data, getTypeToken());
                } else if (json_data.startsWith("{")) {

                    String arrayStr = getArrayStr(json_data);
                    //约定的格式,array通常用list为字段,返回list,简化子类实现
                    if (arrayStr.equals("list")) {

                        return new Gson().fromJson(JSONUtil.getArrayData("list", json_data), getTypeToken());
                    }

                    if (arrayStr != null) {
                        LogUtil.e("typeToken----非list字段: ");
                        return new Gson().fromJson(arrayStr, getTypeToken());
                    }
                    LogUtil.e("data---return null ");
                    return null;
                } else {
                    LogUtil.e("data类型不对: ");
                    return null; // FIXME: 2017/6/23 需要测试没有数组的接口
                }
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())  //回到主线程去处理请求结果
                .subscribe(new Observer<List<T>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(List<T> list) {
                        if (list == null) {
                            LogUtil.e("---list----null: ");

                        }
                        if (page == 1) {
                            mData.clear();
                            setNullPage(list.size() == 0);//首次加载数据是否为空
                        }
                        if (list.size() < OFFSET) {
                            canLoadMore = false;
                        }
                        mData.addAll(list);
                        adapter.notifyDataSetChanged();
                        scrollToEnd();
                    }

                    @Override
                    public void onError(Throwable e) {
                        // FIXME: 2017/6/20 如何处理异常
                    }

                    @Override
                    public void onComplete() {


                        refView.onRefreshComplete();
                        if (netUtil.pd != null) {
                            netUtil.pd.cancel();
                        }
                    }
                });
    }

    protected void scrollToEnd() {
    }


    protected void setNetParams() {
        netUtil.showPd("");
        netUtil.setParams("page", page);
        try {
            netUtil.setParams("uid",
                    LoginInfo.getInstance(App.getContext())
                            .getUser().getU_id());
            netUtil.setParams("pwd",
                    LoginInfo.getInstance(App.getContext())
                            .getUser().getPwd());
        } catch (Exception e) {
        }
    }

    /**
     * @return activity布局
     */
    protected abstract int getActivityLayout();

    /**
     * 添加头布局
     */
    protected void addHeadView() {

    }


    protected void preBundle(Bundle savedInstanceState) {
    }

    /**
     * onCreate中,添加header之后,setTitle,findViewById,getData
     */
    protected abstract void preDone();


    /**
     * 处理json中data对应数据,data是{},处理其中的字段
     *
     * @param jsonStr data字段对应数据
     */
    protected void parseJsonStr(String jsonStr) {
    }


    /**
     * @return 返回子类中实际要转换的List<Bean>
     * return new TypeToken<List<UserItem>>() {}.getType();
     */
    //  protected abstract Type getTypeToken();
    protected abstract Type getTypeToken();


    /**
     * @return item的布局文件
     */
    protected abstract int getItemLayout();

    /**
     * 网络设置 new NetUtil()
     */
    protected abstract void setNetUtil();

    /**
     * item的布局的交互
     */
    protected abstract void convert(ViewHolder holder, T item);


    /**
     * 设置上拉下拉类型,在配置下拉属性时配置
     */
    protected void setMode() {

    }

    @Override
    public void onClick(View v) {

    }

    /**
     * 设置空页面
     */
    protected void setNullPage(boolean isNullPage) {
        if (!isNullPage) {
            try {
                listView.removeFooterView(footer);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (isNullPage && listView.getFooterViewsCount() == 1) {
            listView.addFooterView(footer);
        }
    }

    /**
     * 自动刷新
     */
    protected void autoRefresh() {

        refView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        refView.setRefreshing();
        refView.setMode(PullToRefreshBase.Mode.BOTH);
    }

    protected void autoRefreshNoMore() {
        refView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        refView.setRefreshing();
        refView.setMode(PullToRefreshBase.Mode.DISABLED);
    }

    /**
     * 得到json中data中的数组string
     *
     * @param json_data data:{}
     * @return []
     */
    protected abstract String getArrayStr(String json_data);




    public boolean loginStatus() {

        boolean isLogin = (LoginInfo.getInstance(App.getContext())
                .getUser().getU_id() != null);

        if (!isLogin) {
            Intent it = new Intent(this,
                    LoginActivity.class);
            startActivity(it);
        }

        return isLogin;
    }
}
